// http适配器
import 'dart:convert';

import 'package:hi_net/core/hi_error.dart';
import 'package:hi_net/core/hi_net_adapter.dart';
import 'package:hi_net/request/h_base_request.dart';
import 'package:http/http.dart' as http;

class HttpAdapter extends HiNetAdapter {
  @override
  Future<HiNetResponse<T>> send<T>(HBaseRequest request) async {
    var response;
    var error;
    // 1.创建Client
    final client = http.Client();
    try {
      if (request.httpMethod() == HttpMethod.GET) {
        // 如果是get请求
        final url = Uri.parse(request.url());
        http.Response data = await client.get(url);
        response = json.decode(data.body); //转成map

      } else if (request.httpMethod() == HttpMethod.POST) {
        http.Response data = await client.post(request.url(),
            headers: request.header, body: request.params);
        response = json.decode(data.body); //转成map
      }
    } catch (e) {
      // 捕获异常
      error = e;
      response = e.response;
    }
    if (error != null) {
      throw HiNetError(response?.statusCode ?? -1, error.toString(),
          data: buildRes(response, request));
    } else {
      return buildRes(response, request);
    }
  }

  buildRes(response, HBaseRequest request) {
    // hyLog(response, StackTrace.current); //statusCode 应该是Http里面已经处理了
    return HiNetResponse(
        data: response['data'],
        request: request,
        statusCode: response['code'], //有个地方定义为200才是正确
        statusMessage: response['msg'],
        extra: response);
  }
}
